<template>
  <div>ageRef: {{ ageRef < 40 ? ageRef : "约汉光荣退休惹~" }}</div>

  <hr />
  <p>computed实现</p>
  <ul>
    <li v-for="item in hobbies">{{ item }}</li>
  </ul>

  <hr />
  <p>watch实现</p>
  <ul>
    <li v-for="item in hobbiesRef">{{ item }}</li>
  </ul>
</template>

<script setup>
/*
Vue3语法，age每秒+1岁，侦听age的变化，
满60岁时停止age的计时，
页面age显示“约汉光荣退休惹~”,
同时爱好变为钓鱼+养乌龟
*/
import person from "../../mock/data.json";

import { ref, onBeforeUnmount, computed, watchEffect } from "vue";

const ageRef = ref(person.age);
const hobbiesRef = ref(person.hobbies);

let timer = setInterval(() => {
  ageRef.value++;
}, 1000);

onBeforeUnmount(() => timer && clearInterval(timer));

const hobbies = computed(() =>
  ageRef.value > 39 ? ["钓鱼", "养乌龟"] : person.hobbies
);

const stopper = watchEffect(() => {
  if (ageRef.value > 39) {
    hobbiesRef.value = ["钓鱼", "养乌龟"];
    stopper();
    console.log("watch已停止");
  }
});

</script>

<style lang="scss" scoped></style>
